package com.limh.gobang.activity

import android.content.DialogInterface
import android.graphics.Point
import android.util.Log
import android.view.View
import com.limh.gobang.R
import com.limh.gobang.base.BaseActivity
import com.limh.gobang.base.Consts
import com.limh.gobang.base.Consts.bgColor
import com.limh.gobang.bean.Fight
import com.limh.gobang.bean.MsgEvent
import com.limh.gobang.bean.Type
import com.limh.gobang.bean.User
import com.limh.gobang.service.WebConfiguration
import com.limh.gobang.service.client.HttpClient
import com.limh.gobang.service.resource.ResourceAddressHandler
import com.limh.gobang.service.resource.ResourceFightHandler
import com.limh.gobang.service.server.HttpServer
import com.limh.gobang.service.utils.StreamToolkit
import com.limh.gobang.utils.GsonUtils
import com.limh.gobang.utils.QRUtils
import com.limh.gobang.utils.SpUtils
import com.limh.gobang.view.CommDialog
import com.limh.gobang.view.callback.ResultCallback
import kotlinx.android.synthetic.main.activity_play.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @function
 * @author limh
 * @date 2018/4/29 16:00
 */

class PlayActivity : BaseActivity() {
    var webServerConfig: WebConfiguration? = null
    var webClientConfig: WebConfiguration? = null
    private var dialog: CommDialog? = null
    private var httpServer: HttpServer? = null
    private var httpClient: HttpClient? = null
    private lateinit var user: User
    private lateinit var fight: Fight

    override fun findView() {
        setContentView(R.layout.activity_play)
        EventBus.getDefault().register(this)
    }

    override fun initViews() {
        imageRoom.setOnClickListener { showQRcode() }
        txtBtnFail.setOnClickListener { fail() }
        user = GsonUtils.str2Bean(SpUtils.get(this, Consts.SP_USER, "") as String, User::class.java)
        txtName.text = user.username
        txtGrade.text = user.grade
        txtHead.setBackgroundResource(bgColor[user.userbgId!!])
        if (user.username!!.length > 2) {
            txtHead.text = user.username!!.substring(user.username!!.length - 2)
        } else {
            txtHead.text = user.username
        }

        goBang.resultCallback = object : ResultCallback {
            override fun isGameOver(color: String) {
                val toast = when (color) {
                    ResultCallback.BLACK -> "黑棋赢了"
                    else -> "白棋赢了"
                }
                txtBtnFail.isEnabled = false
                showMsgDialog("消息",toast)
            }

            override fun onLocal(color: String, point: Point) {
                if (color == fight.color) {
                    fight.point = point
                    val msgEvent = MsgEvent()
                    msgEvent.code = Type.TYPE_MSG_POINT
                    msgEvent.any = fight
                    httpClient!!.send("/fight", GsonUtils.bean2Str(msgEvent))
                    goBang.isGameOver = true
                }
            }
        }
    }

    override fun initDatas() {
        val type = intent.getStringExtra("type")
        when (type) {
            "server" -> {
                webServerConfig = intent.getParcelableExtra("webConfig")
                Log.d(TAG, "启动服务器：" + webServerConfig.toString())
                if (null != webServerConfig) {
                    showQRcode()
                    httpServer = HttpServer(webServerConfig!!)
                    httpServer!!.registerResourceHandler(ResourceAddressHandler(this))
                    httpServer!!.registerResourceHandler(ResourceFightHandler())
                    httpServer!!.startASync()
                }
            }
            "client" -> {
                imageRoom.visibility = View.GONE
                webClientConfig = intent.getParcelableExtra("webConfig")
                if (null != webClientConfig) {
                    httpClient = HttpClient(webClientConfig!!)
                    val msgEvent = MsgEvent()
                    msgEvent.code = Type.TYPE_RQ_AUTH
                    msgEvent.any = user
                    httpClient!!.send("/auth", GsonUtils.bean2Str(msgEvent))
                }
            }
        }
        fight = intent.getParcelableExtra("fight")
        if (fight.color == ResultCallback.WHITE) {
            imageMeRole.setImageResource(R.drawable.ic_piece_w)
            imageOtherRole.setImageResource(R.drawable.ic_piece_b)
            goBang.isWhite = true
        } else {
            imageMeRole.setImageResource(R.drawable.ic_piece_b)
            imageOtherRole.setImageResource(R.drawable.ic_piece_w)
            goBang.isWhite = true
        }
    }

    /**
     * 显示房间二维码
     */
    fun showQRcode() {
        val str = GsonUtils.bean2Str(webServerConfig!!)
        val builder = CommDialog.Builder(this)
        builder.showImage(QRUtils.createBitmap(str, 300, 300)!!)
        builder.setTitle("扫码加入房间")
        dialog = builder.create()
        dialog!!.show()
    }

    /**
     * 认输
     */
    private fun fail() {
        if (fight.color == ResultCallback.WHITE && goBang.whiteArray.size == 0) {
            showToast("请先落子")
            return
        }
        if (fight.color == ResultCallback.BLACK && goBang.blckArray.size == 0) {
            showToast("请先落子")
            return
        }
        goBang.isGameOver = true
        val msgEvent = MsgEvent()
        msgEvent.code = Type.TYPE_MSG_FAIL
        msgEvent.any = fight
        httpClient!!.send("/fight", GsonUtils.bean2Str(msgEvent))
    }

    /**
     *
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(msgEvent: MsgEvent) {
        Log.e(TAG, "MSG=" + msgEvent.toString())
        when (msgEvent.code) {
            Type.TYPE_RQ_AUTH -> {
                if (dialog!!.isShowing)
                    dialog!!.dismiss()
                val user = GsonUtils.str2Bean(msgEvent.any.toString(), User::class.java)
                txtOtherName.text = user.username
                txtOtherGrade.text = user.grade

                txtOtherHead.setBackgroundResource(bgColor[user.userbgId!!])
                if (user.username!!.length > 2) {
                    txtOtherHead.text = user.username!!.substring(user.username!!.length - 2)
                } else {
                    txtOtherHead.text = user.username
                }
            }
            Type.TYPE_RS_AUTH -> {
                val user = GsonUtils.str2Bean(msgEvent.any.toString(), User::class.java)
                txtOtherName.text = user.username
                txtOtherGrade.text = user.grade
                txtOtherHead.setBackgroundResource(bgColor[user.userbgId!!])
                if (user.username!!.length > 2) {
                    txtOtherHead.text = user.username!!.substring(user.username!!.length - 2)
                } else {
                    txtOtherHead.text = user.username
                }

                webServerConfig = WebConfiguration()
                webServerConfig!!.address = StreamToolkit.getLocalIp(this)
                webServerConfig!!.port = StreamToolkit.getPort()
                Log.d(TAG, "启动服务器：" + webServerConfig.toString())
                httpServer = HttpServer(webServerConfig!!)
                httpServer!!.registerResourceHandler(ResourceFightHandler())
                httpServer!!.startASync()

                val msg = MsgEvent()
                msg.code = Type.TYPE_RQ_WEB
                msg.any = webServerConfig
                httpClient!!.send("/auth", GsonUtils.bean2Str(msg))
            }
            Type.TYPE_RQ_WEB -> {
                webClientConfig = GsonUtils.str2Bean(msgEvent.any.toString(), WebConfiguration::class.java)
                Log.d(TAG, "client=$webClientConfig")
                httpClient = HttpClient(webClientConfig!!)
                goBang.start()
            }
            Type.TYPE_MSG_POINT -> {
                val msg = GsonUtils.str2Bean(msgEvent.any.toString(), Fight::class.java)
                when (msg.color) {
                    ResultCallback.WHITE -> {
                        goBang.whiteArray.add(msg.point!!)
                        goBang.isWhite = false
                    }
                    else -> {
                        goBang.blckArray.add(msg.point!!)
                        goBang.isWhite = true
                    }
                }
                goBang.invalidate()

                goBang.isGameOver = fight.color == msg.color
            }
            Type.TYPE_MSG_FAIL -> {
                val msg = GsonUtils.str2Bean(msgEvent.any.toString(), Fight::class.java)
                goBang.isGameOver = true
                val toast = when (msg.color) {
                    ResultCallback.WHITE -> {
                        "白棋认输"
                    }
                    else -> {
                        "黑棋认输"
                    }
                }
                txtBtnFail.isEnabled = false
                showMsgDialog("消息",toast)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (null != httpServer)
            httpServer!!.stopASync()
    }
}